import { h, ref } from 'vue';

import { Sort } from '@element-plus/icons-vue';
import {
  ElAutocomplete,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElIcon,
} from 'element-plus';

import { requestClient } from '#/api/request';

interface RenderOptions {
  filterData: Record<string, any>;
  sortData: Record<string, any>;
  url?: string;
  pickerDate?: [Date, Date];
  formData?: Record<string, any>;
  checkedGridClassIds?: any[];
  onFilterChange?: () => void;
  onSorterChange?: () => void;
  isSort?: boolean;
}

export function renderFilterHeader(params: any, options: RenderOptions) {
  const {
    filterData,
    sortData,
    url,
    pickerDate,
    formData,
    checkedGridClassIds,
    onFilterChange,
    onSorterChange,
    isSort = true,
  } = options;

  const suggestions = ref<any[]>([]);
  const noData = ref(false);
  const isClearing = ref(false);
  const isInputFocused = ref(false);
  const autocompleteRef = ref<any>(null); // 创建ref来引用ElAutocomplete组件

  // 防抖函数
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  const debounce = (func: Function, wait: number) => {
    let timeout: null | ReturnType<typeof setTimeout> = null;
    return (...args: any[]) => {
      if (timeout) clearTimeout(timeout);
      timeout = setTimeout(() => func(...args), wait);
    };
  };

  // 使用防抖的fetchSuggestions
  const debouncedFetchSuggestions = debounce(
    // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
    async (queryStr: string, cb?: Function) => {
      suggestions.value = [];
      noData.value = false;

      // 核心逻辑：区分清空操作和点击输入框获取默认数据的场景
      if (!url) {
        if (cb) cb(suggestions.value);
        return;
      }

      // 清空操作：isClearing为true时不发起请求
      if (isClearing.value) {
        isClearing.value = false;
        if (cb) cb(suggestions.value);
        return;
      }

      // 点击输入框获取默认数据：isInputFocused为true且queryStr为空时允许发起请求
      // 正常输入场景：queryStr不为空时发起请求
      if (queryStr.trim() || isInputFocused.value) {
        try {
          const { data } = await requestClient.post(url, {
            heardAutoCompleteName: params.column.property,
            keyword: queryStr,
            pickerDate,
            filterData,
            formData,
            checkedGridClassIds,
          });

          const results =
            data.list?.map((item: any) => ({
              value: `${item.value}`,
              label: item.label || `${item.value}`,
            })) || [];

          if (results.length === 0) {
            noData.value = true;
            suggestions.value = [
              {
                value: '',
                label: '无匹配数据',
                isNoDataItem: true,
              },
            ];
          } else {
            suggestions.value = results;
          }
        } catch (error) {
          console.error('搜索失败:', error);
          noData.value = true;
          suggestions.value = [
            {
              value: '',
              label: '请求失败，请重试',
              isNoDataItem: true,
            },
          ];
        }
      }

      // 重置焦点状态
      if (isInputFocused.value) {
        isInputFocused.value = false;
      }

      if (cb) cb(suggestions.value);
    },
    300,
  ); // 300ms防抖

  const handleSort = (value: string) => {
    Object.keys(sortData).forEach((key) => {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      if (key !== params.column.property) delete sortData[key];
    });

    if (value) {
      sortData[params.column.property] = value;
    } else {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      delete sortData[params.column.property];
    }

    onSorterChange?.();
    onFilterChange?.();
  };

  const renderSorter = () => {
    return h(
      ElDropdown,
      {
        class: 'sorter-dropdown',
        style: {
          marginTop: '4px',
          marginRight: '8px',
          float: 'right',
          cursor: 'pointer',
        },
      },
      {
        default: () => h(ElIcon, null, () => h(Sort)),
        dropdown: () =>
          h(ElDropdownMenu, null, () => [
            h(
              ElDropdownItem,
              { onClick: () => handleSort('asc') },
              () => '升序',
            ),
            h(
              ElDropdownItem,
              { onClick: () => handleSort('desc') },
              () => '降序',
            ),
            h(ElDropdownItem, { onClick: () => handleSort('') }, () => '重置'),
          ]),
      },
    );
  };

  const renderAutocomplete = () => {
    return h(
      ElAutocomplete,
      {
        // 修改ref绑定方式，使用回调函数
        ref: (el: any) => (autocompleteRef.value = el),
        modelValue: filterData[params.column.property] || '',
        'onUpdate:modelValue': (value: string) => {
          filterData[params.column.property] = value;
        },
        clearable: true,
        placeholder: '输入关键字搜索',
        filterable: true,
        popperClass: noData.value ? 'no-data-popper' : '',
        fetchSuggestions: (query, cb) => {
          debouncedFetchSuggestions(query, cb);
        },
        onSelect: () => {
          if (autocompleteRef.value) {
            // 使用setTimeout确保查询完成后再失去焦点
            setTimeout(() => {
              if (
                autocompleteRef.value &&
                typeof autocompleteRef.value.blur === 'function'
              ) {
                autocompleteRef.value.blur();
              }
            }, 100);
          }
        },
        onClear: () => {
          isClearing.value = true; // 标记为清空操作
          // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
          delete filterData[params.column.property];
          onFilterChange?.();
        },
        onKeyup: (event: KeyboardEvent) => {
          if (
            event.key === 'Enter' && // onFilterChange?.();
            // 按下回车键后，让输入框失去焦点
            autocompleteRef.value
          ) {
            // 使用setTimeout确保查询完成后再失去焦点
            setTimeout(() => {
              if (
                autocompleteRef.value &&
                typeof autocompleteRef.value.blur === 'function'
              ) {
                autocompleteRef.value.blur();
              }
            }, 100);
          }
        },
        // 添加鼠标离开输入框时触发查询的功能
        onBlur: () => {
          // 当用户输入内容后离开输入框时，触发查询
          const currentValue = filterData[params.column.property] || '';
          if (currentValue.trim()) {
            // 使用setTimeout确保在失去焦点后延迟执行，避免与其他事件冲突
            setTimeout(() => {
              onFilterChange?.();
            }, 100);
          }
        },
        onFocus: () => {
          isInputFocused.value = true; // 标记为输入框获得焦点
          const currentValue = filterData[params.column.property] || '';
          // 当输入框为空时，主动触发一次请求来获取默认数据
          if (!currentValue.trim()) {
            setTimeout(() => {
              debouncedFetchSuggestions('', (results: any[]) => {
                if (results && results.length > 0) {
                  // 如果有结果，更新建议列表（注意：这里不直接调用cb，由debouncedFetchSuggestions内部处理）
                }
              });
            }, 100);
          }
        },
        size: 'small',
        style: { width: '100%' },
      },
      {
        default: (scope: { item: any }) => {
          if (scope.item?.isNoDataItem) {
            return h(
              'div',
              {
                class: 'no-data-item',
                style: {
                  color: '#999',
                  textAlign: 'center',
                  cursor: 'default',
                },
              },
              scope.item.label,
            );
          }
          return h('div', null, scope.item?.label || '');
        },
      },
    );
  };

  return h('div', { class: 'filter-header' }, [
    h('div', { class: 'header-title' }, [
      h('span', { class: 'title-text' }, params.column.title),
      isSort && renderSorter(),
    ]),
    h(
      'div',
      {
        class: 'header-filter',
      },
      renderAutocomplete(),
    ),
  ]);
}
